<script setup>
import {
  inject,
  nextTick,
  onBeforeUnmount,
  onMounted,
  ref,
  shallowRef,
  watch,
} from 'vue'
import { getBaseMapList } from '@/api/manager/dataManage/baseMap.js'
import {
  fetchCameraDeviceList,
  fetchGnssSensor,
  fetchStaticMonitorDevice,
  fetchYsyCameraDeviceList,
} from '@/api/manager/dataManage/deviceManage.js'
import '@/utils/measure.js'
import { getHelper } from '@/utils/map/index.js'
import { addBillboardClickEvent } from '@/views/new-screen/components/billbordClick.js'
import { useMapEvent } from '@/hooks/useMapEvent.js'
import SpjkIcon from '@/assets/imgs/spjk-tree-icon.png'
import { getDatacatalog } from '@/api/manager/dataManage/layerManage.js'
import { ElMessage } from 'element-plus'
import { useDict } from '@/hooks/useDict.js'
import mitter from '@/utils/eventBus'

const { dict, getDictValue, getDictStyle } = useDict(['tcfwlx'])

const toolActive = ref('')

const props = defineProps({
  menuActive: String,
})

const layerTreeRef = ref()

let measure, _viewer, _layerManager

const toolList = [
  {
    parentClass: 'diqiu',
    type: 'layer',
  },
  {
    parentClass: 'len',
    type: 'length',
  },
  {
    parentClass: 'area',
    type: 'area',
  },
  {
    parentClass: 'clear',
    type: 'clear',
  },
]

const mapId = inject('mapId')

const isFirstLoad = ref(true)

const isDefaultAddLayer = ref(true)

const handleMapToolClick = (type) => {
  // if (type !== 'layer') {
  //   measure._drawLayer.entities.removeAll()
  //   measure.clearAll()
  // }
  switch (type) {
    case 'length':
      if (toolActive.value !== type) {
        measure.drawLineMeasureGraphics({
          clampToGround: true,
          callback: () => {},
        })
      }
      break
    case 'area':
      if (toolActive.value !== type) {
        measure.drawAreaMeasureGraphics({
          clampToGround: true,
          callback: () => {},
        })
      }
      break
    case 'clear':
      measure._drawLayer.entities.removeAll()
      measure.clearAll()
      break
    case 'layer':
      measure._drawLayer.entities.removeAll()
      measure.clearAll()
      break
    default:
      break
  }
  toolActive.value = toolActive.value === type ? '' : type
  if (toolActive.value == 'clear') {
    setTimeout(() => {
      toolActive.value = ''
    }, 100)
  }
}

  // http://219.153.12.167:45910/vec/Mapnik/{z}/{x}/{y}.png 矢量底图
  // http://219.153.12.167:45910/vec/building/{z}/{x}/{y}.png 建筑物服务
  // http://219.153.12.167:45910/vec/Region/{z}/{x}/{y}.png 边界
const baseMapList = ref([
  {
    type: 'basemap',
    name: '底图数据',
    children: [
      // {
      //   id: 'vec',
      //   url: 'https://{s}.tianditu.gov.cn/vec_w/wmts?tk=a49a9220798216424e34b531cb3fa5b2&service=WMTS&version=1.0.0&request=GetTile&LAYER=vec&style=default&format=tiles&TileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}',
      //   name: '电子地图',
      //   type: 'tdt',
      //   img: vectorImg,
      // },
      // {
      //   id: 'img',
      //   url: 'https://{s}.tianditu.gov.cn/img_w/wmts?tk=a49a9220798216424e34b531cb3fa5b2&service=WMTS&version=1.0.0&request=GetTile&LAYER=img&style=default&format=tiles&TileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}',
      //   name: '遥感影像',
      //   type: 'tdt',
      //   img: imgImg,
      // },
      // {
      //   id: 'dark',
      //   url: 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}',
      //   name: '深色底图',
      //   type: 'xyz',
      //   img: threeImg,
      // },
    ],
  },
])

const deviceLayerItem = {
  type: 'device',
  name: '设备数据',
  children: [
    {
      name: '监控视频',
      children: [
        {
          id: 'video',
          name: '监控视频',
          icon: SpjkIcon,
          type: 'billboard',
          dataList: [
            {
              id: '12',
              status: 'online',
              img: 'img/video.png',
              selectImg: '',
              position: [106.50167889877335, 29.794468517069404],
            },
            {
              id: '13',
              status: 'warning',
              img: 'img/video-warning.png',
              selectImg: '',
              position: [106.50439352843257, 29.794252598871918],
            },
          ],
        },
      ],
    },
    {
      name: '电子围栏',
      children: [
        // {
        //   id: 'entity',
        //   type: 'weilan',
        //   name: '监控视频',
        //   icon: SpjkIcon,
        //   positions: [
        //     {
        //       lng: 106.50232362788314,
        //       lat: 29.796165051803207,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50432642504106,
        //       lat: 29.79561034111532,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50433761355669,
        //       lat: 29.794880052459877,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50439650050912,
        //       lat: 29.7941628018438,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50425619143574,
        //       lat: 29.79337752291002,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50397026251471,
        //       lat: 29.79277503239375,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.5037115079798,
        //       lat: 29.792677781628008,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50162568107635,
        //       lat: 29.793420946528503,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50130486359802,
        //       lat: 29.7936254568077,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50176887340942,
        //       lat: 29.7946582180181,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50213614057685,
        //       lat: 29.795765683626307,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50212693225481,
        //       lat: 29.795765683692792,
        //       alt: 0,
        //     },
        //     {
        //       lng: 106.50232362788314,
        //       lat: 29.796165051803207,
        //       alt: 0,
        //     },
        //   ],
        // },
        {
          id: 'maichong',
          name: '脉冲探测器',
          type: 'park_range',
          url:
            window.mapConfig?.parkRange?.find((item) => item.name === '蔡家')
              ?.url || '',
        },
      ],
    },
    {
      name: '监测设备',
      children: [
        {
          id: 'gnss',
          name: 'GNSS',
          type: 'billboard',
        },
        {
          id: 'liefengji_qingjiaoyi',
          name: '裂缝计、倾角仪',
          type: 'billboard',
        },
      ],
    },
    {
      name: '无人道闸',
      children: [
        {
          name: '道闸',
        },
      ],
    },
    {
      name: '人员门禁',
      children: [
        {
          name: '门禁',
        },
      ],
    },
  ],
}

const areaPoint = {
  id: 'areaPoint',
  // name: '监控视频',
  name: '地图标记',
  // icon: SpjkIcon,
  type: 'areaBillboard',
  dataList: [
    {
      id: '1012',
      status: 'online',
      img: 'img/img_dwd.png',
      img1: 'img/img_mc_d.png',
      selectImg: '',
      label: '潼南区人民政府',
      position: [105.84025, 30.190993],
    },
    // {
    //   id: '1012',
    //   status: 'online',
    //   img: 'img/img_dwd.png',
    //   img1: 'img/img_mc_d.png',
    //   selectImg: '',
    //   label: '蔡家片区',
    //   position: [106.47109548446635, 29.73975697792697],
    // },
    // {
    //   id: '1013',
    //   status: 'warning',
    //   img: 'img/img_dwd.png',
    //   img1: 'img/img_mc_d.png',
    //   selectImg: '',
    //   label: '水土片区',
    //   position: [106.49705909773948, 29.78377663396722],
    // },
    // {
    //   id: '1014',
    //   status: 'online',
    //   img: 'img/img_dwd.png',
    //   img1: 'img/img_mc_d.png',
    //   selectImg: '',
    //   label: '东阳片区',
    //   position: [106.44018023300839, 29.844724987354713],
    // },
    // {
    //   id: '1015',
    //   status: 'online',
    //   img: 'img/img_dwd.png',
    //   img1: 'img/img_mc_d.png',
    //   selectImg: '',
    //   label: '龙凤片区',
    //   position: [106.43325643263053, 29.81269767856384],
    // },
    // {
    //   id: '1016',
    //   status: 'online',
    //   img: 'img/img_dwd.png',
    //   img1: 'img/img_mc_d.png',
    //   selectImg: '',
    //   label: '三花石片区',
    //   position: [106.4037757296289, 29.8617693969814],
    // },
    // {
    //   id: '1017',
    //   status: 'online',
    //   img: 'img/img_dwd.png',
    //   img1: 'img/img_mc_d.png',
    //   selectImg: '',
    //   label: '三胜片区',
    //   // position: [106.415395500215, 29.849897500765422],
    //   position: [106.4915054, 29.7747591],
    // },
    // {
    //   id: '1018',
    //   status: 'online',
    //   img: 'img/img_dwd.png',
    //   img1: 'img/img_mc_d.png',
    //   selectImg: '',
    //   label: '歇马片区',
    //   position: [106.35178419837278, 29.750401139813498],
    // },
    // {
    //   id: '1019',
    //   status: 'online',
    //   img: 'img/img_dwd.png',
    //   img1: 'img/img_mc_d.png',
    //   selectImg: '',
    //   label: '澄江片区',
    //   position: [106.37861082088573, 29.866375520098817],
    // },
    // {
    //   id: '1020',
    //   status: 'online',
    //   img: 'img/img_dwd.png',
    //   img1: 'img/img_mc_d.png',
    //   selectImg: '',
    //   label: '南岸片区',
    //   position: [106.55547449961588, 29.523322894550624],
    // },
  ],
}

const layerList = shallowRef([
  {
    type: 'layer',
    name: '图层数据',
    children: [
      // {
      //   name: '区域范围',
      // },
      // {
      //   id: 'caijia_qingxie',
      //   url: window.mapConfig.caijiaQingxie.url,
      //   name: '蔡家倾斜影像',
      //   type: 'qingxie',
      //   heightOffset: window.mapConfig.caijiaQingxie.heightOffset,
      // },
      // {
      //   id: 'sanhuashi_qingxie',
      //   url: window.mapConfig.sanhuashiQingxie.url,
      //   name: '三花石倾斜影像',
      //   type: 'qingxie',
      //   heightOffset: window.mapConfig.sanhuashiQingxie.heightOffset,
      // },
      // {
      //   id: 'tileset',
      //   url: 'b3dm/tileset.json',
      //   name: '城市白模',
      //   type: 'baimo',
      // },
    ],
  },
  // {
  //   name: '园区点位',
  //   type: 'point',
  //   children: [
  //     {
  //       id: 'areaPoint',
  //       name: '园区点位',
  //     },
  //   ],
  // },
  // deviceLayerItem,
])

// if (Array.isArray(window?.mapConfig?.layerExt)) {
//   layerList.value[0].children.push(...window.mapConfig.layerExt)
// }
//
// if (Array.isArray(window?.mapConfig?.parkRange)) {
//   layerList.value[0].children.push({
//     id: 'parkRange',
//     name: '园区范围',
//     children: window.mapConfig.parkRange,
//   })
// }

const diff = (arr1, arr2) => {
  let add = [...arr2.filter((x) => !arr1.includes(x))]
  let del = [...arr1.filter((x) => !arr2.includes(x))]
  return { add, del }
}

const activeBasemap = ref('')

const { setEvent, getEvent, removeEvent } = useMapEvent()

/**
 * 获取底图数据
 */
const fetchBaseMap = () => {
  // http://219.153.12.167:45910/vec/Mapnik/{z}/{x}/{y}.png 矢量底图
  // http://219.153.12.167:45910/vec/building/{z}/{x}/{y}.png 建筑物服务
  // http://219.153.12.167:45910/vec/Region/{z}/{x}/{y}.png 边界

  baseMapList.value[0].children = [
    {
      id: '10001',
      name: '矢量底图',
      url: 'http://219.153.12.167:45910/vec/Mapnik/{z}/{x}/{y}.png',
      type: '22',
    }
  ]
  const baseMap = baseMapList.value[0].children[0]
  handleBaseMapChange(baseMap)
  return

  const resList = [
    {
        "pkid": "c238b446368c4f3986864745efcab286",
        "mapName": "遥感影像",
        "fileId": "48cacdd9ab7140c9b4dd8c391e189ad3",
        "isDefault": 1,
        "mapUrl": "https://{s}.tianditu.gov.cn/img_w/wmts?tk=a49a9220798216424e34b531cb3fa5b2&service=WMTS&version=1.0.0&request=GetTile&LAYER=img&style=default&format=tiles&TileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}",
        "createTime": "2023-12-28 03:33:21",
        "updateTime": "2025-04-17 02:27:30",
        "serviceType": "21",
        "fileUrl": "http://172.20.10.8:10033/48cacdd9ab7140c9b4dd8c391e189ad3/遥感影像.png",
        "terrainService": ""
    },
    {
        "pkid": "93ac5a6d5c0f473fa939222780348101",
        "mapName": "电子地图",
        "fileId": "346dcdeb9c2e4bbb80264de48689e055",
        "isDefault": 0,
        "mapUrl": "https://{s}.tianditu.gov.cn/vec_w/wmts?tk=a49a9220798216424e34b531cb3fa5b2&service=WMTS&version=1.0.0&request=GetTile&LAYER=vec&style=default&format=tiles&TileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}",
        "createTime": "2024-02-23 06:54:46",
        "updateTime": "2025-04-17 02:27:24",
        "serviceType": "21",
        "fileUrl": "http://172.20.10.8:10033/346dcdeb9c2e4bbb80264de48689e055/电子地图.png",
        "terrainService": ""
    }
  ]
  baseMapList.value[0].children = resList.map((item) => {
    return {
      id: item.pkid,
      url: item.mapUrl,
      name: item.mapName,
      type: item.serviceType,
      img: item.fileUrl,
      isDefault: item.isDefault,
    }
  })
  const defaultItem = baseMapList.value[0].children.find(
    (item) => item.isDefault === 1,
  )
  handleBaseMapChange(defaultItem || baseMapList.value[0].children[0])
  return
  
  getBaseMapList({
    pageIndex: 1,
    pageSize: 99,
  }).then((res) => {
    if (res.success) {
      if (res.data.list && res.data.list.length) {
        baseMapList.value[0].children = res.data.list.map((item) => {
          return {
            id: item.pkid,
            url: item.mapUrl,
            name: item.mapName,
            type: item.serviceType,
            img: item.fileUrl,
            isDefault: item.isDefault,
          }
        })
        const defaultItem = baseMapList.value[0].children.find(
          (item) => item.isDefault === 1,
        )
        handleBaseMapChange(defaultItem || baseMapList.value[0].children[0])
      }
    } else {
      ElMessage.error(res.message || '请求底图数据错误')
    }
  })
}

const getLayerDataList = () => {
  const layer = [
    {
      type: 'layer',
      name: '图层数据',
      children: [
        {
          id: '10002',
          name: '建筑物服务',
          type: 'qingxie',
          url: 'http://219.153.12.167:45910/vec/building/{z}/{x}/{y}.png',
          heightOffset: 0,
        },
        {
          id: '10003',
          name: '边界',
          type: 'qingxie',
          url: 'http://219.153.12.167:45910/vec/building/{z}/{x}/{y}.png',
          heightOffset: 0,
        }
      ],
    },
    {
      name: '园区点位',
      type: 'point',
      children: [
        {
          id: 'areaPoint',
          name: '园区点位',
        },
      ],
    },
  ]
  layerList.value = layer

  return
  getDatacatalog({
    catalogType: 5,
  }).then((res) => {
    if (res.success) {
      const data = res.data[0]?.children || []
      const layerData = data.map((res) => {
        return {
          id: res.pkid,
          name: res.catalogName,
          children:
            res.resources?.map((item) => {
              return {
                id: item.pkid,
                name: item.resourceName,
                type: item.serviceType,
                url: item.serviceUrl,
              }
            }) || [],
        }
      })
      const parkRangeData = layerData.find((item) => item.name === '园区范围')
      const layer = [
        {
          type: 'layer',
          name: '图层数据',
          children: layerData,
        },
        {
          name: '园区点位',
          type: 'point',
          children: [
            {
              id: 'areaPoint',
              name: '园区点位',
            },
          ],
        },
        deviceLayerItem,
      ]
      layerList.value = layer
      // if (Array.isArray(window?.mapConfig?.layerExt)) {
      //   layerList.value[0].children.push(...window.mapConfig.layerExt)
      // }

      // if (Array.isArray(window?.mapConfig?.parkRange)) {
      //   layerList.value[0].children.push({
      //     id: 'parkRange',
      //     name: '园区范围',
      //     children: window.mapConfig.parkRange,
      //   })
      // }

      // window.mapConfig?.parkRange?.forEach((item) => {
      //   _layerManager.addLayer(item, false)
      // })
      nextTick(() => {
        if (parkRangeData) {
          layerTreeRef.value.setChecked(parkRangeData.id, true, true)
          setTimeout(() => {
            isDefaultAddLayer.value = false
          }, 1000)
        }
      })
    } else {
      ElMessage.error(res.message || '请求图层数据错误')
    }
  })
}

const onParkChange = (parkName) => {
  const parkRangeList = layerList.value[0].children.find(
    (item) => item.name === '园区范围',
  )
  if (parkRangeList) {
    const findParkRange = parkRangeList.children.find((item) =>
      parkName.includes(item.name),
    )
    const findPoint = areaPoint.dataList.find((item) => item.label === parkName)
    if (findParkRange) {
      // 找到园区范围图层数据
      const findParkRangeNode = layerTreeRef.value?.getNode(findParkRange.id)
      if (findParkRangeNode) {
        if (!findParkRangeNode.checked) {
          layerTreeRef.value?.setChecked(findParkRange.id, true)
          return
        }
      }
      if (findPoint) {
        _viewer.camera.flyTo({
          destination: new window.Cesium.Cartesian3.fromDegrees(
            findPoint.position[0],
            findPoint.position[1],
            3000,
          ),
          orientation: {
            heading: window.Cesium.Math.toRadians(0),
            pitch: window.Cesium.Math.toRadians(-90),
            roll: 0,
          },
        })
      }
    } else {
      // 未找到园区范围图层数据
      const findPoint = areaPoint.dataList.find(
        (item) => item.label === parkName,
      )
      if (findPoint) {
        _viewer.camera.flyTo({
          destination: new window.Cesium.Cartesian3.fromDegrees(
            findPoint.position[0],
            findPoint.position[1],
            3000,
          ),
          orientation: {
            heading: window.Cesium.Math.toRadians(0),
            pitch: window.Cesium.Math.toRadians(-90),
            roll: 0,
          },
        })
      }
    }
  }
}

onMounted(async () => {
  const { map, layerManager } = await getHelper(mapId)
  _viewer = map
  measure = new Cesium.Measure(map)
  _layerManager = layerManager

  fetchBaseMap()

  getLayerDataList()

  const eventKey = 'billboardClick'
  if (!getEvent(eventKey)) {
    const handler = new Cesium.ScreenSpaceEventHandler(map.scene.canvas)
    setEvent(eventKey, handler)
    addBillboardClickEvent(map, handler)
  }

  // window.mapConfig?.parkRange?.forEach((item) => {
  //   _layerManager.addLayer(item, false)
  // })

  mitter.on('switchPark', onParkChange)

  nextTick(() => {
    isFirstLoad.value = false

    // layerTreeRef.value.setChecked('caijia_qingxie', true)
  })
})

watch(
  () => props.menuActive,
  (val) => {
    if (val === 'home') {
      if (isFirstLoad.value) {
        setTimeout(() => {
          // console.log(_layerManager)
          _layerManager.addLayer(areaPoint)
        }, 1000)
      } else {
        layerTreeRef.value?.setChecked('areaPoint', true)
      }
    } else {
      if (isFirstLoad.value) {
        _layerManager.removeLayer(areaPoint)
      } else {
        layerTreeRef.value?.setChecked('areaPoint', false)
      }
    }
  },
  {
    immediate: true,
    // deep: true,
  },
)

const handleBaseMapChange = (item) => {
  if (!item.id) return
  activeBasemap.value = item.id
  _layerManager.setBasemapLayer(item.id, item.name, item.type, item.url)
  // switch (item.type) {
  //   case 'tdt':
  //     _layerManager.setBasemapLayer(item.id, item.name, '26', item.url)
  //     break
  //   case 'xyz':
  //     _layerManager.setBasemapLayer(item.id, item.name, '22', item.url)
  //     break
  //   default:
  //     break
  // }
}

const addTerrain = async () => {
  if (_viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider) {
    _viewer.terrainProvider = await Cesium.CesiumTerrainProvider.fromUrl(
      window.mapConfig.terrainUrl,
    )
  }
}

const removeTerrain = () => {
  if (_viewer.terrainProvider instanceof Cesium.CesiumTerrainProvider) {
    _viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider()
  }
}

const handleCheckChange = (data, checked) => {
  if (!isFirstLoad.value) {
    if (data.type) {
      if (checked) {
        if (data.type === 'billboard' && data.name === '监控视频') {
          fetchCameraDeviceList({
            pageIndex: 1,
            pageSize: 9999,
          })
            .then((res) => {
              if (res.success) {
                const cameraList = res.data.list.filter((item) => {
                  if (item.position) {
                    if (item.position.split(',').length === 2) {
                      return true
                    }
                  }
                  return false
                })
                const dataList = cameraList.map((item) => {
                  return {
                    id: item.pkid,
                    position: item.position.split(','),
                    img: 'img/video.png',
                    meta: {
                      id: item.pkid,
                      nickName: item.nickName,
                      type: 'monitor',
                    },
                  }
                })

                fetchYsyCameraDeviceList({
                  pageIndex: 1,
                  pageSize: 9999,
                }).then((res) => {
                  if (res.success) {
                    const cameraList = res.data.list.filter((item) => {
                      if (item.position) {
                        if (item.position.split(',').length === 2) {
                          return true
                        }
                      }
                      return false
                    })
                    cameraList.forEach((item) => {
                      dataList.push({
                        id: item.pkid,
                        position: item.position.split(','),
                        img: 'img/video.png',
                        meta: {
                          id: item.pkid,
                          hls: item.hls,
                          nickName: item.nickName || item.channelName || '',
                          type: 'monitor',
                        },
                      })
                    })
                    const dataParams = {
                      id: data.id,
                      type: 'billboard',
                      dataList: dataList,
                    }
                    _layerManager.addLayer(dataParams, !isDefaultAddLayer.value)
                  }
                })
                // fetch('monitor.geojson', {
                //   method: 'GET',
                // }).then(async (res) => {
                //   const geojson = await res.json()
                //   geojson.features.forEach((item) => {
                //     dataList.push({
                //       position: item.geometry.coordinates,
                //       img: 'img/video.png',
                //       meta: {
                //         type: 'monitor',
                //       },
                //     })
                //   })
                //   const dataParams = {
                //     id: data.id,
                //     type: 'billboard',
                //     dataList: dataList,
                //   }
                //   _layerManager.addLayer(dataParams, !isDefaultAddLayer.value)
                //   // if (dataList.length) {
                //   //   const dataParams = {
                //   //     id: data.id,
                //   //     type: 'billboard',
                //   //     dataList: dataList,
                //   //   }
                //   //   _layerManager.addLayer(dataParams, !isDefaultAddLayer.value)
                //   // }
                // })
              } else {
                ElMessage.error(res.message || '请求监控视频数据错误')
              }
            })
            .catch((err) => {
              ElMessage.error(err)
            })
        } else if (data.type === 'billboard' && data.name === 'GNSS') {
          fetchGnssSensor({
            pageIndex: 1,
            pageSize: 9999,
          })
            .then((res) => {
              if (res.list && Array.isArray(res.list)) {
                const gnssList = res.list.filter((item) => {
                  if (item.position) {
                    if (item.position.split(',').length === 2) {
                      return true
                    }
                  }
                  return false
                })
                const dataList = gnssList.map((item) => {
                  return {
                    id: item.pkid,
                    position: item.position.split(','),
                    img: 'img/bt_gnss.png',
                  }
                })
                if (dataList.length) {
                  const dataParams = {
                    id: data.id,
                    type: 'billboard',
                    dataList: dataList,
                  }
                  _layerManager.addLayer(dataParams, !isDefaultAddLayer.value)
                }
              } else {
                ElMessage.error('请求GNSS数据错误')
              }
            })
            .catch((err) => {
              ElMessage.error(err)
            })
        } else if (
          data.type === 'billboard' &&
          data.name === '裂缝计、倾角仪'
        ) {
          fetchStaticMonitorDevice({
            pageIndex: 1,
            pageSize: 9999,
          })
            .then((res) => {
              if (res.list && Array.isArray(res.list)) {
                const deviceList = res.list.filter((item) => {
                  if (item.position) {
                    if (item.position.split(',').length === 2) {
                      return true
                    }
                  }
                  return false
                })
                const dataList = deviceList.map((item) => {
                  return {
                    id: item.pkid,
                    position: item.position.split(','),
                    img: 'img/bt_lfz.png',
                  }
                })
                if (dataList.length) {
                  const dataParams = {
                    id: data.id,
                    type: 'billboard',
                    dataList: dataList,
                  }
                  _layerManager.addLayer(dataParams, !isDefaultAddLayer.value)
                }
              } else {
                ElMessage.error('请求裂缝计、倾角仪数据错误')
              }
            })
            .catch((err) => {
              ElMessage.error(err)
            })
        } else {
          _layerManager.addLayer(data, !isDefaultAddLayer.value)
        }
      } else {
        _layerManager.removeLayer(data)
      }

      // const checkedKeys = layerTreeRef.value.getCheckedKeys(true)
      const checkedNodes = layerTreeRef.value.getCheckedNodes(true, false)
      const checkedKeys = checkedNodes.map((node) => node.id)
      // console.log({ checkedKeys, checkedNodes })
      if (checkedNodes.some((node) => node.name.indexOf('倾斜') !== -1)) {
        addTerrain()
      } else {
        removeTerrain()
      }
    } else {
      if (data.id === 'areaPoint') {
        if (checked) {
          _layerManager.addLayer(areaPoint)
        } else {
          _layerManager.removeLayer(areaPoint)
        }
      }
    }
  }
}

onBeforeUnmount(() => {
  mitter.off('changePark')

  if (measure) {
    measure._drawLayer.entities.removeAll()
    measure.clearAll()
  }
  const eventKey = 'billboardClick'
  removeEvent(eventKey)
})
</script>

<template>
  <div class="map-tools">
    <span
      v-for="(item, index) in toolList"
      :key="index"
      :class="[
        'icon',
        item.parentClass,
        toolActive === item.type ? 'active' : '',
      ]"
      @click="handleMapToolClick(item.type)"
    >
      <i :class="item.type"></i>
    </span>
  </div>
  <div class="layer-manager" v-show="toolActive === 'layer'">
    <el-scrollbar>
      <el-tree
        :data="baseMapList"
        show-checkbox
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        :render-after-expand="false"
        class="basemap-tree"
      >
        <template #default="{ node, data }">
          <span
            @click="handleBaseMapChange(node.data)"
            :class="[
              'custom-tree-node',
              node.data.id === activeBasemap ? 'active' : '',
            ]"
          >
            <el-image
              v-if="node.data.type !== 'basemap'"
              :src="node.data.img"
              fit="cover"
            >
              <template #placeholder>
                <div class="image-placeholder"></div>
              </template>
              <template #error>
                <div class="image-error">
                  <span>加载失败</span>
                </div>
              </template>
            </el-image>
            <span :class="node.data.type !== 'basemap' ? 'name' : ''">{{
              node.data.name
            }}</span>
          </span>
        </template>
      </el-tree>
      <el-tree
        ref="layerTreeRef"
        :data="layerList"
        show-checkbox
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        :default-checked-keys="['areaPoint', 'parkRange']"
        @check-change="handleCheckChange"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <el-image
              v-if="node.data.icon"
              :src="node.data.icon"
              class="icon"
            ></el-image>
            <span>{{ node.data.name }}</span>
          </span>
        </template>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<style scoped lang="scss">
.map-tools {
  position: absolute;
  top: 102px;
  left: -42px;
  display: flex;
  flex-direction: column;

  .icon {
    width: 36px;
    height: 36px;
    background: rgba(0, 29, 49, 0.8);
    border: 1px solid #295893;
    cursor: pointer;

    &.active {
      border: none;
      background: url('@/assets/imgs/bt_dt_sel.png') 100% 100% no-repeat;
    }

    &.diqiu {
      margin-bottom: 19px;
    }

    &.area {
      border-top: none;
      margin-bottom: 19px;
    }

    display: flex;
    justify-content: center;
    align-items: center;

    i {
      width: 20px;
      height: 20px;
      background-repeat: no-repeat;
      background-size: 100% 100%;

      &.layer {
        background-image: url('@/assets/imgs/ic_dq_sel.png');
      }

      &.length {
        background-image: url('@/assets/imgs/ic_bc_nor.png');
      }

      &.area {
        background-image: url('@/assets/imgs/ic_hk_nor.png');
      }

      &.clear {
        background-image: url('@/assets/imgs/ic_sc.png');
      }
    }
  }
}

.layer-manager {
  position: absolute;
  top: 102px;
  left: -300px;
  width: 254px;
  height: 613px;
  border: 1px solid;
  border-image: linear-gradient(0deg, #1663c9, #36a8ff) 10 10;
  background: linear-gradient(0deg, #0b2032 0%, #1b61bb 100%);

  padding: 20px 15px;
  //overflow-y: auto;

  :deep(.el-tree) {
    background: transparent;
    color: white;
    --el-tree-expand-icon-color: white;

    .el-tree-node:focus .el-tree-node__content {
      background: transparent;
    }

    .el-tree-node__content:hover {
      background: transparent;
    }

    > .el-tree-node {
      > .el-tree-node__content {
        .el-checkbox {
          display: none;
        }
      }
    }

    .el-tree-node.is-current > .el-tree-node__content {
      // 设置颜色
      background: transparent;
    }

    .custom-tree-node {
      display: flex;
      align-items: center;

      .icon {
        margin-left: -4px;
      }
    }
  }

  :deep(.basemap-tree) {
    ::-webkit-scrollbar {
      height: 6px;
    }

    ::-webkit-scrollbar-track {
      background: #ffffff33;
      border-radius: 3px;
    }

    ::-webkit-scrollbar-thumb {
      background: var(--el-text-color-secondary);
      border-radius: 3px;
    }

    .el-checkbox {
      display: none;
    }

    .el-tree-node__children {
      margin-top: 6px;
      display: flex;
      margin-left: 6px;
      overflow-x: auto;

      .el-tree-node.is-current > .el-tree-node__content {
        // 设置颜色
        background: transparent;
      }

      .el-tree-node {
        width: 71px;
        height: 99px;
        flex-shrink: 0;

        &:not(:last-of-type) {
          margin-right: 4px;
        }

        .el-tree-node__content {
          padding: 0 !important;
          display: block;
          height: 100%;

          .el-icon {
            display: none;
          }

          &:hover {
            background: transparent;
          }

          .custom-tree-node {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            font-size: 12px;
            align-items: center;

            .el-image {
              width: 71px;
              height: 71px;
              flex-shrink: 0;
              margin-bottom: 6px;

              .el-image__inner {
                width: 100%;
                height: 100%;
              }

              .image-placeholder,
              .image-error {
                width: 100%;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                background-color: rgba(240, 240, 240, 0.2);

                span {
                  font-size: 12px;
                }
              }
            }

            .name {
              color: #c4eaff;
            }

            &.active {
              .el-image {
                border: 2px solid #1d8ef5;
              }

              .name {
                color: #1d8ef5;
              }
            }
          }
        }
      }
    }

    .el-tree-node.is-current > .el-tree-node__content {
      // 设置颜色
      background: transparent;
    }
  }
}
</style>
